<template>
  <div class="bg-white rounded-lg p-3 w-full">
    <div class="flex items-center mb-4">
      <div class="flex gap-2">
        <el-input
          v-model="searchForm.keyword"
          placeholder="请输入姓名/电话搜索"
          class="w-60"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearch">
          搜索
        </el-button>
        <el-button type="success" @click="handleAdd">
          新建档案
        </el-button>
      </div>
    </div>

    <el-table
      :data="tableData"
      stripe
      border
      v-loading="loading"
    >
      <el-table-column type="index" label="序号" min-width="60" align="center" />
      <el-table-column prop="name" label="姓名" min-width="100" />
      <el-table-column prop="gender" label="性别" min-width="80" align="center">
        <template #default="{ row }">
          {{ row.gender === '1' ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column prop="age" label="年龄" min-width="80" align="center" />
      <el-table-column prop="height" label="身高(cm)" min-width="100" align="center" />
      <el-table-column prop="bloodType" label="血型" min-width="100" align="center">
        <template #default="{ row }">
          {{ getBloodTypeName(row.bloodType) }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="联系电话" min-width="140" />
      <el-table-column label="操作" min-width="100" fixed="right">
        <template #default="{ row }">
          <el-button type="info" link @click="handleView(row)">
            查看
          </el-button>
          <el-button type="primary" link @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="warning" link @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:page="currentPage"
      v-model:limit="pageSize"
      :total="total"
      @change="handlePageChange"
    />

    <!-- 新建/编辑档案对话框 -->
    <Dialog
      v-model="showDialog"
      :title="form.id ? '编辑健康档案' : '新建健康档案'"
      width="50%"
      :confirm-loading="submitLoading"
      @confirm="handleSubmit"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="mt-4"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio :value="'1'">男</el-radio>
            <el-radio :value="'2'">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="form.age" :min="0" :max="150" />
        </el-form-item>
        <el-form-item label="身高(cm)" prop="height">
          <el-input-number v-model="form.height" :min="0" :max="300" :precision="1" />
        </el-form-item>
        <el-form-item label="血型" prop="bloodType">
          <el-select v-model="form.bloodType" placeholder="请选择血型">
            <el-option
              v-for="item in bloodTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Pagination from '@/components/common/pagination.vue'
import Dialog from '@/components/common/Dialog.vue'

// 搜索表单
const searchForm = ref({
  keyword: ''
})

// 表格加载状态
const loading = ref(false)

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)


// 表格数据
const tableData = ref([
  {
    id: 1,
    name: '张三',
    gender: '1',
    age: 25,
    height: 175,
    bloodType: 'A',
    phone: '13800138000'
  },
  {
    id: 2,
    name: '李四',
    gender: '2',
    age: 30,
    height: 165,
    bloodType: 'B',
    phone: '13900139000'
  }
])
const total = ref(tableData.value.length)
// 加载数据
const loadTableData = () => {
  loading.value = true
  getHealthRecords({ page: currentPage.value, limit: pageSize.value }).then(res => {
    tableData.value = res.data.list
    total.value = res.data.total
  })
}
// 血型选项
const bloodTypeOptions = [
  { value: 'A', label: 'A型' },
  { value: 'B', label: 'B型' },
  { value: 'O', label: 'O型' },
  { value: 'AB', label: 'AB型' },
  { value: 'OTHER', label: '其他' }
]

// 获取血型名称
const getBloodTypeName = (type) => {
  const option = bloodTypeOptions.find(item => item.value === type)
  return option ? option.label : '-'
}

// 表单相关
const showDialog = ref(false)
const formRef = ref()
const form = ref({
  name: '',
  gender: '1',
  age: 0,
  height: 0,
  bloodType: '',
  phone: ''
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
  height: [{ required: true, message: '请输入身高', trigger: 'blur' }],
  bloodType: [{ required: true, message: '请选择血型', trigger: 'change' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 搜索
const handleSearch = () => {
  // 这里调用后端接口进行搜索
  console.log('搜索关键词：', searchForm.value.keyword)
}

// 新建档案
const handleAdd = () => {
  form.value = {
    name: '',
    gender: '1',
    age: 0,
    height: 0,
    bloodType: '',
    phone: ''
  }
  showDialog.value = true
}

// 查看档案
const handleView = (row) => {
  // 跳转到档案详情页
  console.log('查看档案：', row)
}

// 编辑档案
const handleEdit = (row) => {
  form.value = { ...row }
  showDialog.value = true
}

// 删除档案
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该健康档案吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 这里调用后端接口删除档案
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 提交加载状态
const submitLoading = ref(false)

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 这里调用后端接口保存档案
        await new Promise(resolve => setTimeout(resolve, 1000)) // 模拟接口调用
        ElMessage.success(form.value.id ? '修改成功' : '新建成功')
        showDialog.value = false
        // 刷新列表
        loadTableData()
      } catch (error) {
        console.error(error)
        ElMessage.error('操作失败')
      } finally {
        submitLoading.value = false
      }
    } else {
      console.log('验证失败', fields)
    }
  })
}

// 处理分页变化
const handlePageChange = ({ page, limit }) => {
  
}

</script>

<style scoped>
.el-input-number {
  width: 180px;
}
</style>

